package com.djl.mvc.controller;

import com.djl.crowd.entity.Menu;
import com.djl.crowd.util.ResultEntity;
import com.djl.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author le
 * @Date 2021/11/27 10:55
 * @Version 1.0
 */
@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;

//    @ResponseBody
    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer id) {
        menuService.removeMenu(id);
        return ResultEntity.successWithoutData();
    }

//    @ResponseBody
    @PostMapping("/menu/update.json")
    public ResultEntity<String> updateMenu(Menu menu) {
        menuService.updateMenu(menu);
        return ResultEntity.successWithoutData();
    }

//    @ResponseBody
    @PostMapping("/menu/save/menu.json")
    public ResultEntity<String> saveMenu(Menu menu) {
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

//    @ResponseBody
    @GetMapping("/menu/get/whole/tree.json")
    public ResultEntity<Menu> getWholeTree() {

        List<Menu> menus = menuService.getAll();

        // 声明一个变量用来存储根节点
        Menu root = null;

        // 创建Map对象用来存储id和Menu对象的对应关系以便查找父节点
        Map<Integer, Menu> menuMap = new HashMap<>();

        // 填充MenuMap
        for (Menu menu : menus) {
            menuMap.put(menu.getId(), menu);
        }

        // 再次遍历查找根节点，组装父子节点
        for (Menu menu : menus) {
            Integer pid = menu.getPid();
            // 如果pid为null，则是父节点
            if (pid == null) {
                root = menu;
                continue;
            }

            // 不为null，说明有父节点，根据pid找到对应的Menu对象
            Menu father = menuMap.get(pid);
            // 将当前节点存入到父节点的children集合
            father.getChildren().add(menu);
        }

        // 返回根节点
        return ResultEntity.successWithData(root);

    }


}
